package com.huadao.cart_ccs.data.source.websocket;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class OkWebSocket {
    private OkHttpClient okHttpClient;
    private Request request;
    private WebSocket webSocket;
    private String url;

    public OkWebSocket(String url) {
        this.url = url;
        okHttpClient=new OkHttpClient.Builder().build();
        request=new Request.Builder().url(url).build();
    }

    public void connect(){
        okHttpClient.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                super.onOpen(webSocket, response);
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                super.onMessage(webSocket, text);
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                super.onMessage(webSocket, bytes);
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                super.onClosing(webSocket, code, reason);
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                super.onClosed(webSocket, code, reason);
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t,Response response) {
                super.onFailure(webSocket, t, response);
            }
        });
    }

    public void send(String text){
        webSocket.send(text);
    }

    public void send(ByteString byteString){
        webSocket.send(byteString);
    }
}
